package struts.action;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.form.ActionFactory;
import struts.form.ActionForm;
import struts.form.FormFactory;
import struts.listener.ActionListener;
import struts.xml.XMLBean;

public class ActionServlet extends HttpServlet {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ActionServlet.class);

	private static final long serialVersionUID = 1L;

	public ActionServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String charset = this.getInitParameter("charset");
		if (charset != null && !"".equals(charset)) {
			request.setCharacterEncoding(charset);
			response.setCharacterEncoding(charset);
		}
		String path = getPath(request.getServletPath());
		@SuppressWarnings("unchecked")
		Map<String, XMLBean> map = (Map<String, XMLBean>) this.getServletContext().getAttribute(ActionListener.STRUTS);
		XMLBean xmlBean = map.get(path);
		if (xmlBean != null) {
			String beanClass = xmlBean.getFormClass();
			ActionForm form = FormFactory.createForm(beanClass, request);
			String actionClass = xmlBean.getActionClass();
			Action action = ActionFactory.createAction(actionClass);
			String url = action.execute(request, form, xmlBean.getForward());
			request.getRequestDispatcher(url).forward(request, response);
		}else{
			request.getRequestDispatcher("index.jsp").forward(request, response);
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

	public void init() throws ServletException {
		// Put your code here
	}

	private String getPath(String servletPath) {
		System.out.println(servletPath.split("\\.")[0]);
		return servletPath.split("\\.")[0];
	}

}
